import { Router } from '@angular/router';
import {AfterViewChecked, Component, OnInit, ViewChild} from '@angular/core';
import {FormGroup, FormBuilder, Validators, NgForm} from '@angular/forms';
import {validateFormControls} from '../../../shared/util/validate-utils';
import {CacheService} from '../../../shared/service/cache.service';
import {CurrUserService} from '../../../shared/service/curr-user.service';
import {fadeInAnimation} from '../../../routing/route.animation';
import {CurrUserModel} from '../../../shared/models/curr-user.model';
import {LoginService} from '../../../shared/service/login.service';

@Component({
  selector: 'app-pages-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  providers:[LoginService],
  host: {
    '[@fadeInAnimation]': 'true'
  },
  animations: [ fadeInAnimation ]
})
export class LoginComponent implements OnInit  , AfterViewChecked{
  user:any={};
  valForm: NgForm;
  @ViewChild('valForm') currentForm: NgForm;
  formErrors:any = {};
  tipMsg:any;
  currUser:CurrUserModel=  new CurrUserModel(null,null,null);

  valForm1: FormGroup;
  constructor( fb: FormBuilder,
               private router: Router,
               private loginService:LoginService,
               private cacheService:CacheService,
               private currUserService:CurrUserService,) {
    this.valForm1 = fb.group({
      email: [null, Validators.compose([Validators.required])],//, Validators.email
      password: [null, Validators.required],
      remember_me: [null]
    });
  }

  ngOnInit() {
    this.logout();
    this.currUserService.currUserChange.subscribe((currUserModel) => {
      this.currUser = currUserModel;
    });
  }
  submit(form:NgForm){
    for (const i in this.valForm1.controls) {
      this.valForm1.controls[i].markAsDirty();
    }
    if (this.valForm1.valid) {
      console.log('Valid!');
      console.log(this.valForm1.value);
      this.router.navigate(['auth-guard']);
    }
    // if (form.valid) {
    //   this.loginService.login(this.user).then((user)=>{
    //     // console.log(user);
    //     //登录成功
    //     this.cacheService.setCurrUserInfo(user);
    //     let currUser = new CurrUserModel(user.id,user.realName,user.groupId);
    //     this.currUserService.setCurrUser(currUser);
    //     this.router.navigate(['/auth-guard']);
    //   },(error)=>{//后台验证错误再根据具体错误指定 control dialog
    //     console.log("登录户出错",error);
    //     let jsonResult = JSON.parse(error._body)
    //     if(jsonResult.errCode=="SERVICE/ERR_PASSWORD_INCORRECT"||jsonResult.errCode=="SERVICE/ERR_SYS_USER_NOT_EXIST"){
    //       this.tipMsg = "用户名或密码不正确！"
    //     }else {
    //       this.tipMsg = jsonResult.msg
    //     }
    //     setTimeout((data)=>{
    //       this.tipMsg = null;
    //     },3000)
    //   })
    // }else {//点击提交时验证表单合法性
    //   validateFormControls(form.controls,this.valForm.form,this.formErrors)
    // }
  }
  ngAfterViewChecked() {
    this.formChanged();//输入时实时提示错误
  }
  formChanged() {
    if (this.currentForm === this.valForm) {
      return;
    }
    this.valForm = this.currentForm;
    if (this.valForm) {
      this.valForm.valueChanges
        .subscribe(data => this.onValueChanged(data));
    }
  }
  onValueChanged(data?: any) {
    if (!this.valForm) { return; }
    validateFormControls(data,this.valForm.form,this.formErrors)
  }

  logout(){
    // this.loginService.logout().then((result)=>{
    //   this.currUserService.clearCurrUser()
    //   this.cacheService.clear()
    // })
  }
}
